package com.pj.point.pri;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.pj.point.R;
import com.pj.point.home.PaintActivity;
import com.pj.point.litepal.CreateData;
import com.pj.point.litepal.DiaryJavaBean;
import com.pj.point.util.alert.AlertUtil;
import com.pj.point.util.key.SoftKeyBoardListener;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@SuppressLint("ResourceAsColor")
public class PrivateDiary extends AppCompatActivity {

    private TextView createTimeText;
    private EditText title;
    private LinearLayout bottomView;
    private LinearLayout insertSound;
    private LinearLayout insertPhoto;
    private LinearLayout createGesture;
    private LinearLayout insertOther;
    private LinearLayout createList;
    private Activity activity;
    private int index = 0;
    private Map<View, String> map;
    private Map<View, String> resource;
    private String isOpen;
    private DiaryJavaBean diaryData;
    private String time;
    private boolean isSave = false;
    private Uri uri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_diary);
        activity = this;
        initBar();
        initView();
        keyInputListener();
        bottomViewInit();
        isOpen();
    }

    private void isOpen() {
        isOpen = getIntent().getStringExtra("isOpen");
        if (isOpen != null) {
            diaryData = LitePal.where("createTime=?", isOpen).findFirst(DiaryJavaBean.class, true);
            title.setText(diaryData.getTitle());
            time = diaryData.getCreateTime();
            createTimeText.setText(time);
            List<CreateData> content = diaryData.getContent();
            if (content != null) {
                for (CreateData i : content) {
                    switch (i.getKey()) {
                        case "text": {
                            EditText text = getText();
                            text.setText(i.getValue());
                            addView(text, "text");
                            break;
                        }
                        case "audio": {
                            insertSound(i.getValue(), false);
                            break;
                        }
                        case "image": {
                            insertImage(i.getValue(), false);
                            break;
                        }
                    }
                    i.delete();
                    diaryData.setContent(null);
                    diaryData.save();
                }
            }
        }
        EditText text = getText();
        addView(text, "text");

    }

    private void initBar() {
        ActionBar bar = getSupportActionBar();
        bar.setDisplayHomeAsUpEnabled(true);
        bar.setTitle("查看日记");
    }

    @Override
    public void onBackPressed() {
        if (!isSave){
            save(false);
            super.onBackPressed();
        }
    }

    private void bottomViewInit() {
        insertSound.setOnClickListener(view -> {
            Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
            startActivityForResult(intent, 1);
        });

        insertPhoto.setOnClickListener(v -> {
            BottomSheetDialog dialog = new BottomSheetDialog(PrivateDiary.this);
            View view = LayoutInflater.from(PrivateDiary.this).inflate(R.layout.dialog_bottom, null);
            TextView takePhoto = view.findViewById(R.id.take_photo);
            TextView selectPhoto = view.findViewById(R.id.select_photo);
            TextView cancel = view.findViewById(R.id.cancel);

            takePhoto.setOnClickListener(vv -> {
                takePhoto();
                dialog.dismiss();
            });

            selectPhoto.setOnClickListener(vv -> {
                selectPhoto();
                dialog.dismiss();
            });
            cancel.setOnClickListener(vv -> {
                dialog.dismiss();
            });
            dialog.setContentView(view);
            dialog.show();
        });

        createGesture.setOnClickListener(view -> {
            startActivityForResult(new Intent(PrivateDiary.this, PaintActivity.class), 4);
        });

        insertOther.setOnClickListener(view -> {
            Toast.makeText(this, "功能开发中...", Toast.LENGTH_SHORT).show();
        });

    }

    private void selectPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, 2);
    }

    private void takePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, 3);
    }

    private void keyInputListener() {
        SoftKeyBoardListener.setListener(PrivateDiary.this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                bottomView.setVisibility(View.VISIBLE);
            }

            @Override
            public void keyBoardHide(int height) {
                bottomView.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.diary_state_page_nav, menu);
        menu.getItem(2).setTitle("取消设置私密");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.send_nav: {
                send();
                break;
            }
            case R.id.theme_nav: {
                changeTheme();
                break;
            }
            case R.id.private_nav: {
                cancelPrivate();
                break;
            }
            case R.id.delete_nav: {
                delete();
                break;
            }
            default: {
                save(true);
                setResult(-1);
                finish();
            }
        }
        return super.onOptionsItemSelected(item);
    }

    private void save(boolean b) {
        List<CreateData> newData = new ArrayList<>();
        for (int i = 0; i < createList.getChildCount(); i++) {
            View child = createList.getChildAt(i);
            if (map.containsKey(child)) {
                switch (Objects.requireNonNull(map.get(child))) {
                    case "text": {
                        EditText text = (EditText) child;
                        String str = text.getText().toString().trim();
                        if (!str.equals(""))
                            newData.add(new CreateData("text", str, time));
                        break;
                    }
                    case "image": {
                        newData.add(new CreateData("image", resource.get(child), time));
                        break;
                    }
                    case "audio": {
                        newData.add(new CreateData("audio", resource.get(child), time));
                        break;
                    }
                }
            }
        }
        String createTime = time;
        String title = this.title.getText().toString().trim();
        diaryData.setContent(newData);
        diaryData.setTitle(title);
        List<CreateData> content = diaryData.getContent();
        for (CreateData data : content) {
            data.save();
        }
        diaryData.setIsPrivate(b);
        diaryData.save();
        isSave = true;
    }

    @Override
    protected void onDestroy() {
        if (!isSave) {
            save(true);
        }
        setResult(-1);
        super.onDestroy();
    }

    private void delete() {
        Toast.makeText(this, "删除日记", Toast.LENGTH_SHORT).show();
    }

    private void cancelPrivate() {
        save(false);
        setResult(-1);
        finish();
    }

    private void changeTheme() {
        Toast.makeText(this, "功能开发中...", Toast.LENGTH_SHORT).show();
    }

    private void send() {
        BottomSheetDialog dialog = new BottomSheetDialog(PrivateDiary.this);
        View view = LayoutInflater.from(this).inflate(R.layout.send_bottom_layout, null);
        LinearLayout sendQq = (LinearLayout) view.findViewById(R.id.send_qq);
        LinearLayout sendWechat = (LinearLayout) view.findViewById(R.id.send_wechat);
        LinearLayout sendWebo = (LinearLayout) view.findViewById(R.id.send_webo);
        sendQq.setOnClickListener(v -> {
            Toast.makeText(this, "qq点击", Toast.LENGTH_SHORT).show();
            dialog.dismiss();
        });

        sendWechat.setOnClickListener(v -> {
            Toast.makeText(this, "微信点击", Toast.LENGTH_SHORT).show();
            dialog.dismiss();
        });

        sendWebo.setOnClickListener(v -> {
            Toast.makeText(this, "微博点击", Toast.LENGTH_SHORT).show();
            dialog.dismiss();
        });
        dialog.setContentView(view);
        dialog.show();
    }


    private void initView() {
        map = new HashMap<>();
        resource = new HashMap<>();
        createTimeText = (TextView) findViewById(R.id.create_time_text);
        title = (EditText) findViewById(R.id.title);
        bottomView = (LinearLayout) findViewById(R.id.bottom_view);
        insertSound = (LinearLayout) findViewById(R.id.insert_sound);
        insertPhoto = (LinearLayout) findViewById(R.id.insert_photo);
        createGesture = (LinearLayout) findViewById(R.id.create_gesture);
        insertOther = (LinearLayout) findViewById(R.id.insert_other);
        createList = (LinearLayout) findViewById(R.id.create_list);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1: {
                    @SuppressLint("Recycle") Cursor query = getContentResolver().query(data.getData(), new String[]{"_data"}, null, null, null);
                    query.moveToFirst();
                    String path = query.getString(0);
                    insertSound(path, true);
                    break;
                }
                case 2: {
                    Uri uri = data.getData();
                    @SuppressLint("Recycle") Cursor query = getContentResolver().query(uri, new String[]{"_data"}, null, null, null);
                    query.moveToFirst();
                    String path = query.getString(0);
                    insertImage(path, true);
                    break;
                }
                case 3:{
                    @SuppressLint("Recycle") Cursor query = getContentResolver().query(uri, new String[]{"_data"}, null, null, null);
                    query.moveToFirst();
                    String path = query.getString(0);
                    insertImage(path,true);
                    break;
                }
                case 4: {
                    insertImage(data.getStringExtra("path"), true);
                    break;
                }
            }
        }
    }

    @SuppressLint("SimpleDateFormat")
    private void insertSound(String path, boolean flag) {
        View v = LayoutInflater.from(activity).inflate(R.layout.player, null);
        PlayerView playController = (PlayerView) v.findViewById(R.id.player_controller);
        ExoPlayer player = new ExoPlayer.Builder(activity).build();
        MediaItem mediaItem = MediaItem.fromUri(Uri.parse(path));
        player.setMediaItem(mediaItem);
        playController.setPlayer(player);
        addView(v, "audio", path);
        if (flag) {
            addView(getText(), "text");
        }
        v.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                AlertUtil.show(activity, "删除提醒", "确定要删除所选内容吗？", b -> {
                    if (b) {
                        removeView(v);
                    }
                });
                return false;
            }
        });
    }

    private void insertImage(String path, boolean flag) {
        View v = LayoutInflater.from(this).inflate(R.layout.image_item, null);
        ImageView imageView = v.findViewById(R.id.image_item_img);
        Glide.with(this).load(path).into(imageView);
        addView(v, "image", path);
        if (flag) {
            addView(getText(), "text");
        }
        v.setOnLongClickListener(view -> {
            AlertUtil.show(activity, "删除提醒", "确定要删除所选内容吗？", b -> {
                if (b) {
                    removeView(v);
                }
            });
            return false;
        });
    }

    private void removeView(View v) {
        createList.removeView(v);
        map.remove(v);
        resource.remove(v);
        isSave = false;
    }

    private void addView(View v, String image, String path) {
        createList.addView(v);
        map.put(v, image);
        resource.put(v, path);
        isSave = false;
    }


    private void addView(View v, String type) {
        createList.addView(v);
        map.put(v, type);
        isSave = false;
    }

    public EditText getText() {
        EditText editText = new EditText(activity);
        editText.setBackground(null);
        editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        editText.setMinHeight(150);
        return editText;
    }

}